/*
*	(*^。^*) TFrameWork License (*^。^*)
*/

/*
 *  Title :  
 *          
 *  Description :  
 *          
 *          
 *  Date : 
 *
 *  Author : DengPing
 *
 *  Modify : 
 */
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;

namespace TFrameWork.Module.ActionEditor
{
    internal partial class ActionEditor
    {
        private string skillEditorScenePath
        {
            get { return ActionEditorUtility.GetAssetPath("t:SceneAsset", "ActionEditorScene.unity"); }
        }

        private const string previewCharacterParentPath = "PreviewRoot";

        private bool isChangeScene = false;
        private string oldScenePath;

        private Button LoadEditorSceneButton;
        private Button SettingsButton;
        
        private ObjectField PreviewCharacterObjectField;
        private ObjectField ActionDataObjectField;
        
        private IntegerField CurrentFrameField;
        private IntegerField FrameCountField;
        private Button TotalFrame;
        
        private GameObject currentPreviewCharacterObj;

        private IntegerField CurrentFrameRate;
        private TextField DataName;

        public GameObject PreviewCharacterObj
        {
            get
            {
                if (currentPreviewCharacterObj == null)
                {
                    if (PreviewCharacterObjectField.value != null)
                    {
                        PreviewCharacterObjectFieldValue(PreviewCharacterObjectField.value);
                    }else if (ActionEditor.Instance.ActionData != null)
                    {
                        var path = ActionEditor.Instance.ActionData.defaultPrePrefab;
                        if (!string.IsNullOrEmpty(ActionEditor.Instance.ActionData.defaultPrePrefab))
                        {
                             var go = AssetDatabase.LoadAssetAtPath<Object>(path);
                             PreviewCharacterObjectField.value = go; 
                             PreviewCharacterObjectFieldValue(go);
                        }
                    }
                }
                return currentPreviewCharacterObj;
            }
        }

        private void InitTopMenu()
        {
            LoadEditorSceneButton = _root.Q<Button>(nameof(LoadEditorSceneButton));
            LoadEditorSceneButton.clicked += LoadEditorSceneButtonClick;

            SettingsButton = _root.Q<Button>(nameof(SettingsButton));
            Texture2D img = EditorGUIUtility.IconContent("d_Settings Icon").image as Texture2D;
            SettingsButton.style.backgroundImage = new StyleBackground(img);
            SettingsButton.clicked += SettingButtonClick;

            PreviewCharacterObjectField = _root.Q<ObjectField>(nameof(PreviewCharacterObjectField));
            PreviewCharacterObjectField.RegisterValueChangedCallback(PreviewCharacterObjectFieldValueChanged);

            ActionDataObjectField = _root.Q<ObjectField>(nameof(ActionDataObjectField));
            ActionDataObjectField.RegisterValueChangedCallback(ActionDataObjectFieldValueChanged);

            CurrentFrameField = _root.Q<IntegerField>(nameof(CurrentFrameField));
            CurrentFrameField.RegisterValueChangedCallback(CurrentFrameFieldValueChanged);

            FrameCountField = _root.Q<IntegerField>(nameof(FrameCountField));
            FrameCountField.RegisterValueChangedCallback(FrameCountValueChanged);

            TotalFrame = _root.Q<Button>(nameof(TotalFrame));
            TotalFrame.clicked += TotalFrameButtonClick;

            CurrentFrameRate = _root.Q<IntegerField>(nameof(CurrentFrameRate));
            CurrentFrameRate.RegisterValueChangedCallback(CurrentFrameRateChange);

            DataName = _root.Q<TextField>(nameof(DataName));
            DataName.RegisterValueChangedCallback(DAtaNameChange);

            LoadEditorSceneButton.text = "加载编辑器场景";
        }

        private void DAtaNameChange(ChangeEvent<string> evt)
        {
            if (!_actionData.SkillName.Equals(evt.newValue))
            {
                _actionData.SkillName = evt.newValue;
            }
        }

        private void CurrentFrameRateChange(ChangeEvent<int> evt)
        {
            if (_actionData.FrameRote != evt.newValue)
            {
                if (evt.newValue < 1)
                {
                    CurrentFrameRate.value = 1;
                    _actionData.FrameRote = 1;
                    return;
                }

                _actionData.FrameRote = evt.newValue;
            }
        }

        private void TotalFrameButtonClick()
        {
            int totalFrame = -1;
            if (_actionData != null)
            {
                foreach (var data in _actionData.trackDataList)
                {
                    foreach (TrackItemData trackData in data.trackDatas)
                    {
                        foreach (var dataEvent in trackData.events)
                        {
                            if (dataEvent.startIndex + dataEvent.durationIndex > totalFrame)
                            {
                                totalFrame = dataEvent.startIndex + dataEvent.durationIndex;
                            }
                        }
                    }
                }

                if (totalFrame != -1)
                {
                    if (CurrentSelectFrameIndex > totalFrame)
                    {
                        CurrentSelectFrameIndex = 0;
                    }
                    CurrentFrameCount = totalFrame;
                }
            }
            else
            {
                CurrentFrameCount = 100;
            }
            
        }

        public bool OnEditorScene
        {
            get
            {
                string currentScenePath = EditorSceneManager.GetActiveScene().path;
                return currentScenePath == skillEditorScenePath;
            }
        }
        
        private void CurrentFrameFieldValueChanged(ChangeEvent<int> evt)
        {
            if (CurrentSelectFrameIndex != evt.newValue) CurrentSelectFrameIndex = evt.newValue;
        }

        private void FrameCountValueChanged(ChangeEvent<int> evt)
        {
            if (CurrentFrameCount != evt.newValue) CurrentFrameCount = evt.newValue;
        }

        // 加载编辑器场景
        private void LoadEditorSceneButtonClick()
        {
            var currentScenePath = EditorSceneManager.GetActiveScene().path;
            if (currentScenePath !=skillEditorScenePath)
            {

                oldScenePath = currentScenePath;
                EditorSceneManager.OpenScene(skillEditorScenePath);
                var array = oldScenePath.Split('/');
                var sceneName = array[array.Length - 1].Split('.')[0];
                LoadEditorSceneButton.text = "返回 " + sceneName +" 场景";
                isChangeScene = true;
            }
            else
            {
                if (!string.IsNullOrEmpty(oldScenePath) && EditorSceneManager.GetActiveScene().path != oldScenePath)
                {
                    EditorSceneManager.OpenScene(oldScenePath);
                    LoadEditorSceneButton.text = "加载编辑器场景";
                    isChangeScene = true;
                }
                else
                {
                    
                }
            }
        }

        private void OnGUITop()
        {

            if (isChangeScene)
            {
                var currentScenePath = EditorSceneManager.GetActiveScene().path;
                if (currentScenePath != skillEditorScenePath)
                {
                    LoadEditorSceneButton.text = "加载编辑器场景";
                }
                else
                {
                    if (oldScenePath != null && EditorSceneManager.GetActiveScene().path != oldScenePath)
                    {                
                        var array = oldScenePath.Split('/');
                        var sceneName = array[array.Length - 1].Split('.')[0];;
                        LoadEditorSceneButton.text = "返回 " + sceneName + " 场景";
                    }
                    else
                    {

                    }
                }

                isChangeScene = false;
            }
        }

        private void SettingButtonClick()
        {
            var menu = new GenericMenu();
            menu.AddItem(new GUIContent("创建新的技能文件"), false, CreateNewActionData);
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("保存"), false, SaveConfig);
            menu.AddItem(new GUIContent("导出Json"),false,ExportJson);
            menu.AddSeparator("");
            menu.AddItem(new GUIContent("设置"), false, SettingChangePanel);
            
            menu.ShowAsContext();
        }

        private void SettingChangePanel()
        {
            EditorApplication.ExecuteMenuItem("Edit/Preferences...");
            
        }

        private void ExportJson()
        {
            Debug.LogError("功能暂时未开发");
        }

        // 角色预制体修改
        private void PreviewCharacterPrefabObjectFieldValueChanged(Object obj)
        {
            // 避免在其他场景实例化
            string currentScenePath = EditorSceneManager.GetActiveScene().path;
            if (currentScenePath != skillEditorScenePath)
            {
                return;
            }

            // 销毁旧的
            if (currentPreviewCharacterObj != null) DestroyImmediate(currentPreviewCharacterObj);
            Transform parent = GameObject.Find(previewCharacterParentPath).transform;
            if (parent != null && parent.childCount > 0)
            {
                DestroyImmediate(parent.GetChild(0).gameObject);
            }

            // 实例化新的
            if (obj != null)
            {
                currentPreviewCharacterObj =
                    Instantiate(obj as GameObject, Vector3.zero, Quaternion.identity, parent);
                currentPreviewCharacterObj.transform.localRotation = Quaternion.Euler(0, 0, 0);
                
                if (currentPreviewCharacterObj.GetComponent<TimeLineAction>() == null)
                {
                    currentPreviewCharacterObj.AddComponent<TimeLineAction>();
                }
            }
        }

        // 角色预览对象修改
        private void PreviewCharacterObjectFieldValueChanged(ChangeEvent<UnityEngine.Object> evt)
        {
            if(evt.newValue == null) return;
            PreviewCharacterObjectFieldValue(evt.newValue);
        }

        private void PreviewCharacterObjectFieldValue(Object obj)
        {
            if(obj == null) return;
            var path = AssetDatabase.GetAssetPath(obj);
            if (string.IsNullOrEmpty(path))
            {
                //场景对象
                currentPreviewCharacterObj = (GameObject)obj;
            }
            else
            {
                if (ActionEditor.Instance.ActionData != null)
                {
                    ActionEditor.Instance.ActionData.defaultPrePrefab = path;
                }
                //预制体
                PreviewCharacterPrefabObjectFieldValueChanged(obj);
            }
        }

        
        /// <summary>
        /// 当配置数据发送改变
        /// </summary>
        /// <param name="evt"></param>
        private void ActionDataObjectFieldValueChanged(ChangeEvent<UnityEngine.Object> evt)
        {
            if (_actionData != null)
            {
                EditorUtility.SetDirty(_actionData);
                AssetDatabase.SaveAssetIfDirty(_actionData);
            }
            
            _actionData = evt.newValue as ActionData;
            CurrentSelectFrameIndex = 0;
            if (_actionData == null)
            {
                CurrentFrameCount = 100;
                
                var display = CreateDataBg.style.display;
                display.value = DisplayStyle.Flex;
                CreateDataBg.style.display = display;
            }
            else
            {
                CurrentFrameCount = _actionData.FrameCount;
                
                var path = _actionData.defaultPrePrefab;
                if (string.IsNullOrEmpty(path))
                {
                    if (PreviewCharacterObjectField.value == null)
                    {
                        var go = AssetDatabase.LoadAssetAtPath<Object>(path);
                        PreviewCharacterObjectField.value = go;
                        PreviewCharacterObjectFieldValue(go);
                    }
                }
                
                var display = CreateDataBg.style.display;
                display.value = DisplayStyle.None;
                CreateDataBg.style.display = display;
            }
            
            // 刷新轨道
            ResetLoadTrack();
        }

    }
}
